package com.buba.utils;

/**
 * LC: 2023-02-22 14:52
 */

import com.alipay.api.java_websocket.WebSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/webSocket")
@Slf4j
public class WebSocketServer {// 通过 WebSocketServer 进行数据传输

    private Session session;

    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 有新的连接，总数
     * @param session
     */
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketSet.add(this);
        log.info("有新的连接，总数:{}",webSocketSet.size());
    }

    /**
     * 链接断开，总数
     */
    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        log.info("链接断开，总数：{}",webSocketSet.size());
    }

    /**
     * 收到客户端发来的消息
     * @param message
     */
    @OnMessage
    public void onMessage(String message){
        log.info("收到客户端发来的消息:{}", message);
    }

    /**
     * 发送消息
     * @param message
     */
    public void sendMessage(String message){
        for (WebSocketServer webSocket : webSocketSet){
            log.info("消息，message={}",message);
            try {
                webSocket.session.getBasicRemote().sendText(message);
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
